package com.yan.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yan.common.exception.NoStockException;
import com.yan.common.to.mq.OrderTo;
import com.yan.common.to.mq.StockDetailTo;
import com.yan.common.to.mq.StockLockedTo;
import com.yan.common.utils.PageUtils;
import com.yan.common.utils.Query;
import com.yan.common.utils.R;
import com.yan.gulimall.ware.dao.WareSkuDao;
import com.yan.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.yan.gulimall.ware.entity.WareOrderTaskEntity;
import com.yan.gulimall.ware.entity.WareSkuEntity;
import com.yan.gulimall.ware.feign.OrderFeignService;
import com.yan.gulimall.ware.service.WareOrderTaskDetailService;
import com.yan.gulimall.ware.service.WareOrderTaskService;
import com.yan.gulimall.ware.service.WareSkuService;
import com.yan.gulimall.ware.vo.OrderItemVo;
import com.yan.gulimall.ware.vo.OrderVo;
import com.yan.gulimall.ware.vo.SkuHasStockVo;
import com.yan.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }


    private void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> voList = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();

            // 查询sku的库存
            // select sum(stock-stock_locked) from `wms_ware_sku` where sku_id = 1
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());

        return null;
    }

    /**
     * 锁定库存方法
     *
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单，为了追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);
        // TODO 需要解决的,使用死信MQ来完成最终一致性

        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.selectWareIdHasSKuStockList(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        // 锁定库存
        for (SkuWareHasStock stock : collect) {
            Boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareId = stock.getWareId();
            if (wareId == null || wareId.size() > 0) {
                throw new NoStockException(skuId);
            }
            for (Long ware : wareId) {
                // 成功返回1,否则返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    // 库存锁定成功
                    skuStocked = true;
                    // 保存到DB,且通知MQ
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", stock.getNum(), taskEntity.getId(), ware, 1);
                    orderTaskDetailService.save(entity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, stockDetailTo);
                    stockLockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange",
                            "stock.locked", stockLockedTo);

                    break;
                } else {
                    // 当前仓库锁定失败,尝试下一个仓库
                }
            }
            if (skuStocked == false) {
                // 当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }


        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        System.out.println("收到解锁库存消息");
        StockDetailTo detailTo = to.getDetailTo();
        Long detailToId = detailTo.getId();
        // 查询数据库这个订单相关的锁定信息
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailToId);
        if (byId != null) {
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);

            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });

                if (data == null || data.getStatus() == 4) {
                    // 订单被取消了或不存在...才能解锁库存
                    unlockStock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), detailToId);
                }
            } else {
                // 拒绝消息,让消息重新进入队列,让其他线程消费解锁
                throw new RuntimeException("远程服务调用失败");
            }

        } else {
            // 无需解锁
        }
    }

    /**
     * 防止订单服务造成的卡顿导致的订单状态消息一直无法更改,库存消息优先到期的问题
     * @param to
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        // 查询最新状态
        R orderStatus = orderFeignService.getOrderStatus(orderSn);
        WareOrderTaskEntity orderTask = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = orderTask.getId();
        // 按照工作单找到所有没有解锁的库存,进行解锁。
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unlockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }

    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }

}